#-*- coding: utf-8 -*-
from google.appengine.api import users
from models.main import App_user
from django.http import HttpResponse, HttpResponseRedirect

import datetime

from logics.main import get_user, set_user

def logout(request):
    url = request.GET.get('url', '/')
    request.session['email'] = ''
    return HttpResponseRedirect(users.create_logout_url(url))

class AuthMiddleware(object):
    def process_request(self, request):
        #先判断session
        user_email = request.session.get('email')
        app_user = None
        if user_email:
            app_user =  App_user.all().filter('email', user_email).get()
        else:
            u = users.get_current_user()
            if u:
                user_email = u.email()
                nickname = u.nickname()
                is_admin = users.is_current_user_admin()
                if is_admin:
                    level = 10
                else:
                    level = 1
                app_user = App_user.all().filter('email', user_email).get()
                if app_user is None:
                    app_user = App_user(email = user_email, nickname = nickname, \
                            is_verified = True, add_time = datetime.datetime.utcnow())
                
                app_user.level = level
                app_user.put()

                request.session['email'] = user_email

        request.user = app_user
        set_user(app_user)